<template>
  <div class="app-container">

    <projectView :key="'projectView' + form.projectNo" :datas="form" :column="3" :sizes="'large'"></projectView>
    <el-divider style="font-size: 16px; font-weight: bold;">项目核算信息</el-divider>
    <el-button v-if="form.saleCom == '1'" type="primary" plain :icon="Plus" @click="addProfit()"
      style="margin-bottom: 10px;">添加利润计算</el-button>

    <el-button plain style="margin-bottom: 10px;" v-if="haveNext" type="primary"
      @click="openAllocationDialog()">绩效分配</el-button>

    <el-table :summary-method="getSummary" show-summary :row-class-name="tableRowClassName" border
      :data="accountingList">
      <el-table-column label="类型" align="center" prop="type">
        <template #default="scope">
          <dict-tag :options="profit_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="此类型的结算总额" align="center" width="100" prop="projectAmount" />
      <el-table-column label="项目税额" align="center" width="100" prop="taxAmount" />
      <el-table-column label="项目材料成本" align="center" width="100" prop="materialCost" />
      <el-table-column label="其他成本一(报销费用)" align="center" width="100" prop="costOne" />
      <el-table-column label="其他成本二" align="center" width="100" prop="costTwo" />
      <el-table-column label="其他成本三" align="center" width="100" prop="costThree" />
      <el-table-column label="资金成本" align="center" width="100" prop="fundCost" />
      <el-table-column label="外协人工成本" align="center" width="100" prop="laborCost" />
      <el-table-column label="税率(%)" align="center" prop="rate" />
      <el-table-column label="毛利润" align="center" width="100" prop="profit" />
      <el-table-column label="成本税费" align="center" width="100" prop="costFees" />
      <el-table-column label="差额税费" align="center" width="100" prop="differenceFees" />
      <el-table-column label="税前利润" align="center" width="100" prop="beforeProfit" />
      <el-table-column label="质保金" align="center" width="100" prop="retentionMoney" />
      <el-table-column label="纯利润扣质保金" align="center" width="100" prop="afterProfit" />
      <el-table-column label="项目提成" align="center" width="100" prop="projectCommission" />
      <el-table-column label="操作员" align="center" prop="operator" />
      <el-table-column v-if="form.saleCom == '1'" label="操作" align="center" fixed="right"
        :width="userStore.isMobile ? 80 : 220" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" :disabled="scope.row.audit == '4' && !haveNext"
            @click="handleUpdateProfit(scope.row)">修改</el-button>
          <el-button link type="primary" :disabled="scope.row.audit == '4' && !haveNext"
            @click="handleDeleteProfit(scope.row)">删除</el-button>
          <el-button link type="primary" v-if="!haveNext && scope.row.audit == '1'"
            @click="submitInfo(scope.row, '提交', '2')">确认提交</el-button>
          <el-button link type="primary" v-if="!haveNext && scope.row.audit == '2'"
            @click="submitInfo(scope.row, '撤销', '1')">撤销</el-button>
          <el-button link type="primary" v-if="haveNext && scope.row.audit == '2'"
            @click="submitInfo(scope.row, '通过审核', '4')">通过审核</el-button>
          <el-button link type="primary" v-if="haveNext && scope.row.audit == '2'"
            @click="submitInfo(scope.row, '驳回', '1')">驳回</el-button>
          <el-button link type="primary" v-if="haveNext && scope.row.audit == '4'"
            @click="submitInfo(scope.row, '驳回', '1')">驳回</el-button>
          <el-tooltip content="此操作会重新获取报销费用和人工成本" placement="top">
            <el-button v-if="scope.$index === 0" link type="success" @click="refreshCost(scope.row)"> 重新计算
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <el-divider style="font-size: 16px; font-weight: bold;">参与人员信息</el-divider>
    <el-button v-if="form.saleCom == '1'" type="primary" plain :icon="Plus" @click="addPerson('add')"
      style="margin-bottom: 10px; ">添加参与人员</el-button>
    <el-table :data="personList" border>
      <el-table-column label="标签页" align="center" width="180" prop="phaseName" />
      <el-table-column label="参与人" align="center" width="200" prop="participanName" />
      <el-table-column label="岗位" align="center" prop="postName" />
      <el-table-column label="开始日期" align="center" width="120" prop="startDate" />
      <el-table-column label="结束日期" align="center" prop="endDate" />
      <el-table-column label="备注" align="center" width="120" prop="remark" />
      <el-table-column label="操作员" align="center" prop="operator" />
      <el-table-column label="操作时间" align="center" prop="startDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}") }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="form.saleCom == '1'" label="操作" fixed="right" :width="userStore.isMobile ? 120 : 220"
        align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" :icon="userStore.isMobile ? '' : 'Edit'" :disabled="scope.row.phaseId != 5"
            @click="handleUpdateParticipan(scope.row, scope.$index, 'edit')">修改</el-button>
          <el-button link type="primary" :width="userStore.isMobile ? 120 : 220" :disabled="scope.row.phaseId != 5"
            @click="handleDeleteParticipan(scope.row, scope.$index, 'delete')">删除</el-button>
        </template>
      </el-table-column>
    </el-table>



    <!-- <div class="dialog-footer">
      <el-button v-if="haveNext" type="primary" @click="openAllocationDialog()">绩效分配</el-button>
      <el-popconfirm v-if="status == 1 && haveNext" confirm-button-text="确认" cancel-button-text="取消" title="确认提交到下一步?"
        @confirm="nextPhase">
        <template #reference>
          <el-button type="primary">下一步</el-button>
        </template>
      </el-popconfirm>
      <el-button v-if="status == 1 && haveNext" type="primary" @click="rollBack">回退环节</el-button>
      <el-button type="primary" @click="cancel">关 闭</el-button>
    </div> -->

    <!-- 添加或修改付款对话框 -->

    <el-dialog title="利润计算信息" v-model="openProfit" :width="userStore.isMobile ? '95%' : '900px'" append-to-body>
      <el-form ref="accountingRef" size="large" :model="profitForm" :rules="profitRules" label-width="160px">
        <el-form-item label="类型" prop="type">
          <el-select @change="setTypeName" v-model="profitForm.type" placeholder="请选择类型">
            <el-option v-for="dict in profit_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="此类型的结算总额" prop="projectAmount">
          <el-input type="number" @wheel.native.prevent v-model="profitForm.projectAmount" placeholder="请输入此类型的结算总额" />
        </el-form-item>


        <el-form-item label="项目材料成本" prop="materialCost">
          <el-input type="number" @wheel.native.prevent :disabled="true" v-model="profitForm.materialCost"
            placeholder="请输入项目材料成本" />
        </el-form-item>
        <el-form-item label="其他成本一(报销费用)" prop="costOne">
          <el-input type="number" @wheel.native.prevent :disabled="true" v-model="profitForm.costOne"
            placeholder="请输入其他成本一" />
        </el-form-item>
        <el-form-item label="其他成本二" prop="costTwo">
          <el-input type="number" @wheel.native.prevent v-model="profitForm.costTwo" placeholder="请输入其他成本二" />
        </el-form-item>
        <el-form-item label="其他成本三" prop="costThree">
          <el-input type="number" @wheel.native.prevent v-model="profitForm.costThree" placeholder="请输入其他成本三" />
        </el-form-item>

        <el-form-item label="质保金" prop="retentionMoney">
          <el-input type="number" @wheel.native.prevent v-model="profitForm.retentionMoney" placeholder="请输入质保金" />
        </el-form-item>

        <el-form-item label="占用资金金额" prop="useAmount">
          <el-input type="number" @wheel.native.prevent v-model="profitForm.useAmount" placeholder="" />
        </el-form-item>

        <el-form-item v-if="!userStore.isMobile">
          <el-tag size="small">提示：如有资金占用金额,需要输入资金使用时间以及月利率用于计算资金成本</el-tag>
        </el-form-item>


        <el-form-item label="资金使用时间(月)" prop="costTime">
          <el-input type="number" @wheel.native.prevent v-model="profitForm.costTime" placeholder="资金使用时间" />
        </el-form-item>

        <el-form-item label="月利率" prop="monthRate">
          <el-input type="number" @wheel.native.prevent @blur="handleBlurFundCost()" v-model="profitForm.monthRate"
            placeholder="请输入月利率" />
        </el-form-item>

        <el-form-item label="资金成本" prop="fundCost">
          <el-input type="number" @wheel.native.prevent :disabled="true" v-model="profitForm.fundCost"
            placeholder="请输入资金成本" />
        </el-form-item>

        <el-form-item label="人工成本" prop="laborCost">
          <el-input type="number" disabled @wheel.native.prevent v-model="profitForm.laborCost" placeholder="请输入人工成本" />
        </el-form-item>

        <el-form-item v-if="!userStore.isMobile">
          <el-tag size="small">提示：请在配套施工清单中填写相关费用(总费用为人工成本)</el-tag>
        </el-form-item>


        <el-form-item label="税率(%)" prop="laborCost">
          <el-input type="number" @wheel.native.prevent v-model="profitForm.rate" :disabled="true" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="profitForm.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>

        <el-divider style="font-size: 16px; font-weight: bold;">环节留言</el-divider>
        <el-form-item label="留言" prop="remark">
          <el-input v-model="form.phaseRemark" type="textarea" placeholder="请输入留言" />
        </el-form-item>


      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitProfitForm">确 定</el-button>
          <el-button @click="cancelProfit">取 消</el-button>
        </div>
      </template>

    </el-dialog>
    <el-drawer v-model="openAllocation" :title="drawerTitle" direction="rtl" size="70%">
      <allocation ref="allocationRef"></allocation>
    </el-drawer>



    <!-- 添加或修改项目参加人员子对话框 -->
    <el-dialog title="参与人信息" v-model="openOper" :width="userStore.isMobile ? '95%' : '800px'" append-to-body>
      <el-form ref="participanRef" :model="personForm" :rules="personRules" size="large" label-width="120px">
        <el-form-item label="参与人" prop="participantId">
          <el-select @change="setPersonName" filterable v-model="personForm.participantId" placeholder="请选择参与人"
            clearable style="width: 200px;">
            <el-option v-for="dict in userList" clearable :key="dict.userId" :label="dict.nickName"
              :value="dict.userId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="参与人岗位" prop="postId">
          <el-select @change="setPostName" filterable v-model="personForm.postId" placeholder="请选择岗位" clearable
            style="width: 200px;">
            <el-option v-for="dict in posts" clearable :key="dict.postId" :label="dict.postName"
              :value="dict.postId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker clearable v-model="personForm.startDate" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择开始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker clearable v-model="personForm.endDate" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="personForm.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitPersonForm">确 定</el-button>
          <el-button @click="cancelPerson">取 消</el-button>
        </div>
      </template>
    </el-dialog>


  </div>
</template>

<script setup name="Project">
import {
  saleDetails,
  checkMoney,
  listParticipan, delParticipan, addParticipan, updateParticipan, getPermission,
  getStatus, saveUserTableConfig, getUserTableConfig
} from "@/api/project/project";
import { listAttachment, rollBackPhase } from "@/api/project/project";
import { listPay, listImplement, getTotalCost, addPhase, updatePhase, listAccounting, getAccounting, delAccounting, addAccounting, updateAccounting, updateAudit, checkWait } from "@/api/project/project";
import {
  Plus
} from '@element-plus/icons-vue'
import { getInfo } from "@/api/login";
import { listAllUser, getUser, getPosts } from "@/api/system/user";
import { getCheck, getNextPermission, getDictionary } from "@/api/project/dictionary";
import { totalFee } from "@/api/project/fee";
import { getAllocationMoney } from "@/api/project/allocation";
import { getMatchingTotal } from "@/api/project/matching";

const props = defineProps({
  datas: {
    type: Object, // 指定类型为对象
    required: false, // 是否必填
  },
  column: {
    type: Number, // 指定类型为数字
    default: 3, // 设置默认值为 3
  },
  sizes: {
    default: 'default',
  },
  projectNo: {
    default: '0',
    required: true
  },


});

const { projectNo } = toRefs(props);

const haveNext = ref(false)

function getSummary(param) {
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计';
      return;
    }
    const key = column.property;
    const validKeys = [
      'projectAmount',
      'taxAmount',
      'materialCost',
      'costOne',
      'costTwo',
      'costThree',
      'fundCost',
      'laborCost',
      'profit',
      'costFees',
      'differenceFees',
      'beforeProfit',
      'retentionMoney',
      'afterProfit',
      'projectCommission'
    ];

    if (!validKeys.includes(key)) {
      sums[index] = '';
      return;
    }

    const sum = data.reduce((acc, item) => {
      return acc + (Number(item[key]) || 0);
    }, 0);

    sums[index] = sum.toFixed(2);
  });

  return sums;
}


const addPersonPer = ref(false)
const addFilePer = ref(false)
const addPayPer = ref(false)
const addImplementPer = ref(false)
const addWarrantyPer = ref(false)
const addAccountingPer = ref(false)
const loadingQuery = ref(false)
const cw = ref(false)
const allPer = ref(false)

const { proxy } = getCurrentInstance();
const { profit_type } = proxy.useDict('profit_type');
const { rate_type } = proxy.useDict('rate_type');
const attachmentList = ref([]);
const payList = ref([]);
const posts = ref([])
const userList = ref([])
const projectList = ref([]);
const personList = ref([]);
const implementList = ref([]);
const accountingList = ref([]);
const open = ref(false);
const openView = ref(false);
const isView = ref(false);
const openOper = ref(false);
const openProfit = ref(false);
const loading = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeAcceptTime = ref([]);
const contractAmount = ref(0)
const settlementAmount = ref(0)
const materialCost = ref(-1)
const bxFee = ref()//报销费用
const matchingFee = ref()//人工成本
const finance = ref(false);//当期人员是否是财务
const manger = ref(false);//当前人员是否项目经理
const havePay = ref(false);//是否有添加付款信息的权限
const status = ref("0");
const currenrPhaseId = ref()
const formDisabled = ref(true);
import { ElLoading } from 'element-plus'
import projectView from "../saleProjectView.vue";
import { ref } from "vue";
const data = reactive({
  currentProject: {},
  form: {
    createUserName: null,
    createUserId: null,
    createDeptName: null,
    createDept: null,
    saleCom: '1'
  },
  currentConfig: {

  },
  personForm: {
  },
  fileForm: {

  },
  profitForm: {

  },


  rules: {
    projectName: [{ required: true, message: "项目名称不能为空", trigger: "blur" }],
    approvalDate: [{ required: true, message: "立项日期不能为空", trigger: "blur" }],
    projectType: [{ required: true, message: "项目类型 不能为空", trigger: "blur" }],
  },
  personRules: {
    postId: [{ required: true, message: "岗位不能为空", trigger: "blur" }],
    participantId: [{ required: true, message: "参与人不能为空", trigger: "blur" }],
  },

  profitRules: {
    type: [{ required: true, message: "请选择类型", trigger: "blur" }],
    projectAmount: [{ required: true, message: "结算总金额不能为空", trigger: "blur" }],
    rate: [{ required: true, message: "未找到税率信息，请联系管理员配置", trigger: "blur" }],
    retentionMoney: [{ required: true, message: "必须填写质保金,涉及到绩效分配,没有请填0 ", trigger: "blur" }],

  }


});

function handleUpdateParticipan(row) {
  openOper.value = true
  personForm.value = row

}

//添加参与人员
function addPerson() {
  //重置表单
  resetPer()
  // personList.value = []
  openOper.value = true
  personForm.value.phaseId = 5
}
// 表单重置
function resetPer() {
  personForm.value = {
  };
  proxy.resetForm("participanRef");

}


function setPostName(id) {
  // 筛选 posts.value 中符合条件的对象
  const filteredObjects = posts.value.filter((obj) => obj.postId === id);
  // 清空 projectTypeName 字段
  personForm.value.postName = '';
  console.log("postName", filteredObjects);
  personForm.value.postName = filteredObjects[0].postName
}

function setPersonName(id) {
  // 筛选 posts.value 中符合条件的对象
  const filteredObjects = userList.value.filter((obj) => obj.userId === id);
  // 清空 projectTypeName 字段
  personForm.value.participanName = '';
  console.log("filteredObjects[0]?.nickName", filteredObjects[0]?.nickName);

  personForm.value.participanName = filteredObjects[0]?.nickName
}

/** 提交按钮 */
function submitPersonForm() {
  proxy.$refs["participanRef"].validate(valid => {
    if (valid) {
      personForm.value.projectNo = projectNo.value
      if (personForm.value.id != null) {
        updateParticipan(personForm.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          openOper.value = false;
          getListParticipan(projectNo.value)
        });
      } else {
        addParticipan(personForm.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          openOper.value = false;
          getListParticipan(projectNo.value)
        });
      }
    }
  });
}




function setTypeName(id) {
  //对应的名称
  const filteredObjects = profit_type.value.find(item => item.value == id);
  profitForm.value.typeName = filteredObjects.label
  const result = rate_type.value.find(item => item.label == profitForm.value.typeName);
  console.log("profitForm.value.typeName", profitForm.value.typeName);

  console.log("resultresult", filteredObjects.label, result);
  if (!result) {
    proxy.$modal.msgError("未找到此类型的税率信息，请联系管理员配置");
    return
  }
  profitForm.value.rate = result.value


  if (accountingList.value.length > 0) {
    profitForm.value.materialCost = 0
  } else {
    profitForm.value.materialCost = materialCost.value
  }


}


function handleBlurFundCost() {

  if (!profitForm.value.useAmount) {
    // proxy.$modal.msgSuccess("请输入资金占用金额");
    return
  }

  if (!profitForm.value.costTime) {
    // proxy.$modal.msgSuccess("请输入资金占用时间");
    return
  }

  if (!profitForm.value.monthRate) {
    // proxy.$modal.msgSuccess("请输入月利率");
    return
  }

  const percentage = parseFloat(profitForm.value.monthRate);
  console.log(`月利率: ${percentage}%`);
  // 计算金额并保留两位小数
  profitForm.value.fundCost = parseFloat((profitForm.value.useAmount * profitForm.value.costTime * profitForm.value.monthRate).toFixed(2));
  console.log(`资金成本: ${profitForm.value.fundCost}`);
}



/** 修改付款信息按钮操作 */
async function handleUpdateProfit(row) {
  resetProfit();
  const _Id = row.id || ids.value

  let param1 = {
    projectNo: projectNo.value,
  }

  getAccounting(_Id).then(response => {
    profitForm.value = response.data;
    openProfit.value = true;
  });
}

//重新获取报销费用和人工成本
async function refreshCost(row) {
  resetProfit();
  const _Id = row.id || ids.value

  let param1 = {
    projectNo: projectNo.value,
  }
  const loadingInstance = ElLoading.service({ fullscreen: true, text: '报销费用获取中...' });
  await totalFee(param1).then(response => {
    bxFee.value = response.data;
    console.log("修改按钮获取总报销费用", bxFee.value);
  });

  await getMatchingTotal(param1).then(response => {
    console.log("人工成本", response);
    matchingFee.value = response
  });

  getAccounting(_Id).then(response => {
    profitForm.value = response.data;
    profitForm.value.costOne = bxFee.value
    profitForm.value.laborCost = matchingFee.value
    openProfit.value = true;
    loadingInstance.close()
  });
}


/** 提交按钮 */
function submitProfitForm() {
  proxy.$refs["accountingRef"].validate(valid => {
    if (valid) {
      profitForm.value.projectNo = projectNo.value
      profitForm.value.phaseId = 5
      if (profitForm.value.id != null) {
        updateAccounting(profitForm.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          openProfit.value = false;
          getListParticipan(projectNo.value)
        });
      } else {
        addAccounting(profitForm.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          openProfit.value = false;
          getListParticipan(projectNo.value)
        });
      }
    }
  });
}

/** 删除付款信息按钮操作 */
function handleDeleteProfit(row) {
  const _Id = row.id
  proxy.$modal.confirm('是否确认删除？').then(function () {
    return delAccounting(_Id);
  }).then(() => {
    getListParticipan(projectNo.value)
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}


//添加付款信息 销售负责人添加付款信息？
async function addProfit() {
  let paramCheck = {
    projectNo: projectNo.value,
  }
  const res = await checkWait(paramCheck);

  console.log("判断111111111111111", res);


  resetProfit();

  const loadingInstance = ElLoading.service({ fullscreen: true, text: '成本费用计算中...' });
  // 定义定时任务
  let intervalId = null;

  intervalId = setInterval(() => {
    // 检查 materialCost 是否不等于 -1
    if (materialCost.value != -1 && bxFee.value != undefined && bxFee.value != null && matchingFee.value != null) {
      // 关闭加载状态
      loadingInstance.close();
      // 清除定时任务
      clearInterval(intervalId);
      loadingInstance.close()
      console.log('加载状态已关闭');

      // profitForm.value.projectAmount = contractAmount.value//合同签订金额自动带出 取结算金额？
      profitForm.value.projectAmount = settlementAmount.value ?? contractAmount.value;
      profitForm.value.materialCost = materialCost.value

      console.log('自动带出结算金额', settlementAmount.value);

      //报销费用 材料费用 只能添加一次
      if (accountingList.value.length > 0) {
        profitForm.value.materialCost = 0
        profitForm.value.laborCost = 0
      } else {
        profitForm.value.materialCost = materialCost.value
        profitForm.value.laborCost = matchingFee.value

      }

      profitForm.value.costOne = bxFee.value;
      // personList.value = []
      openProfit.value = true

    }
  }, 500); // 每隔 500ms 检查一次

  let param1 = {
    projectNo: projectNo.value,
  }
  // if (accountingList.value.length == 0) {
  await totalFee(param1).then(response => {
    bxFee.value = response.data;
    console.log("总报销费用", bxFee.value);
  });
  // }

  //需关联管家婆项目 只有第一条才会添加材料成本
  // if(accountingList.value.length == 0){
  await getTotalCost(param1).then((response) => {
    // accountingList.value = response.data;
    materialCost.value = response.data.totalCost
    console.log("获取总成本", response);
  });
  // }


  await getMatchingTotal(param1).then(response => {
    console.log("人工成本addprofit", response);
    matchingFee.value = response

  });


  //报销费用只取一次 人工成本只取一次
  if (accountingList.value.length > 0) {
    bxFee.value = 0
    profitForm.value.costOne = bxFee.value;
    matchingFee.value = 0
    profitForm.value.laborCost = matchingFee.value

  }


}


const { form, personForm, payRules, personRules, profitRules, fileForm, profitForm, currentConfig } = toRefs(data);


function getCurrUser(id) {
  getPosts(id).then(response => {
    console.log("66666666", response);
  });
}


//判断是否是销售负责人 项目经理 销售 财务 商务

async function isSale() {
  let params = {
    projectNo: projectNo.value,
    // phaseId: 1,//立项前期 写死
    postIds: [2, 5, 6, 7]//传入岗位id    需要添加项目经理id 2  销售负责人 5  销售 9 商务 7 财务 6
  }
  havePay.value = await hasPermisson(params)
  console.log("添加付款信息", havePay.value);

}

//是否是财务
async function isFinance() {
  let params = {
    projectNo: projectNo.value,
    // phaseId: 1,//立项前期 写死
    postIds: [2, 6]//传入岗位id    需要添加项目经理id 2  销售负责人 5  销售 9 商务 7 财务 6
  }
  finance.value = await hasPermisson(params)

  console.log("添加财务信息", finance.value);
  isManger()
}



async function hasPermisson(params) {
  const res = await getPermission(params).then((response) => {
    console.log("权限信息", response.data);
    return response.data
  });
  return res
}



function initData() {
  getUser().then(response => {
    const targetIds = [6, 7];
    posts.value = response.posts.filter(post => targetIds.includes(post.postId));
    console.log("岗位信息", response);
  });
  listAllUser().then(res => {
    console.log("userlist", res);
    userList.value = res
  });

  getInfo().then((res) => {
    console.log("当前用户", res);
    getCurrUser(res.user.userId)
  })
    .catch((error) => {
      console.log("error", error);
    });
}



// 取消按钮
function cancel() {

}

// 取消按钮
function cancelProfit() {
  openProfit.value = false;
  resetProfit();
}


//获取用户详细信息
function getUserInfo() {
  getInfo().then((res) => {
    const user = res.user;
    form.value.createUserName = user.nickName;
    form.value.createUserId = user.userId;
    form.value.createDeptName = user.dept.deptName
    form.value.createDept = user.deptId
    console.log("user", form);
  })
    .catch((error) => {
      console.log("error", error);
    });
}
// 表单重置
function reset() {
  form.value = {
    projectNo: null,
    projectName: null,
    createDeptName: null,
    projectAmount: null,
    projectType: null,
    projectUnit: null,
    acceptTime: null,
    customerAddress: null,
    customerName: null,
    housekeeperProject: null,
    phaseCode: null,
    remark: null,
    minProjectAmount: null,
    maxProjectAmount: null
  };
  proxy.resetForm("projectRef");
}


// 表单重置
function resetProfit() {
  profitForm.value = {

  };
  proxy.resetForm("accountingRef");

}



function handleDeleteParticipan(row, index) {
  proxy.$modal
    .confirm('是否确认删除？')
    .then(async () => {
      if (row.id) {
        await delParticipan(row.id)
        proxy.$modal.msgSuccess("删除成功");
      }
      getListParticipan(form.value.projectNo)
    })
    .catch((error) => {
      // 捕获错误并提示用户
      console.error("删除操作失败", error);
      proxy.$modal.msgError("删除失败，请稍后再试");
    });
}


/** 新增按钮操作 */
function handleAdd() {
  formDisabled.value = false
  reset();
  personList.value = []
  open.value = true;
  title.value = "添加项目基本信息";
  form.value.startDate = getCurrentDateTime()
  form.value.approvalDate = getCurrentDate()
  getUserInfo()
}



async function getListParticipan(projectNo) {
  console.log("projectNoprojectNo", projectNo);

  let params = {
    projectNo: projectNo
  }


  listParticipan(params).then((response) => {
    console.log("参与人员", response);
    personList.value = response.data
  });


  listAccounting(params).then((response) => {
    accountingList.value = response.data;
  });


}


import allocation from "../allocation.vue";
const allocationRef = ref()
const drawerTitle = ref('')
const openAllocation = ref(false)
//绩效分配
async function openAllocationDialog() {

  //先检查  对应的款都有没有收到


  console.log("accountingListaccountingList", accountingList);

  if (accountingList.value.length == 0) {
    proxy.$modal.msgError("请先添加利润计算信息");
    return
  }

  for (let index = 0; index < accountingList.value.length; index++) {
    const element = accountingList.value[index];
    console.log("审核audit", element);
    if (element.audit == '2') {//如果有待审核的 提示需要先审核通过
      proxy.$modal.msgError("有待审核的利润计算信息,请先审核通过后再进行绩效分配");
      return
    }
  }


  let param1 = {
    projectNo: projectNo.value,
  }
  const loadingInstance = ElLoading.service({ fullscreen: true, text: '信息校验中获取中...' });
  await totalFee(param1).then(response => {
    bxFee.value = response.data;
  }).finally(() => {
    loadingInstance.close();
  });


  //判断最新报销费用是否和在添加利润计算的时候获取的金额是相等的 
  if (bxFee.value != accountingList.value[0]?.costOne) {
    proxy.$modal.msgError("最新报销费用为" + bxFee.value + "与填写利润计算时的报销费用" + accountingList.value[0]?.costOne + "不相等,请点击重新计算按钮获取最新的报销费用后重新提交");
    return
  }

  saleDetails(projectNo.value).then((response) => {
    form.value = response.data;
    drawerTitle.value = form.value.housekeeperName
    openAllocation.value = true
    // 使用 nextTick 确保组件已经渲染
    nextTick(() => {
      if (allocationRef.value) {
        if (form.value.saleCom == '1') {
          allocationRef.value.initData(form.value, "1", 'accounting');
        } else {
          allocationRef.value.initData(form.value, "2", 'accountingComplete');
        }

      } else {
        console.error("allocationRef is not available yet!");
      }
    });
  });

}

import { getAuditPermission } from "@/api/project/allocation";





//销售负责人提交核算的数据
function submitInfo(row, title, types) {
  profitForm.value = row
  proxy.$modal.confirm('是否确认' + title + '？').then(async function () {
    if (profitForm.value.id != null) {
      profitForm.value.audit = types
      await updateAudit(profitForm.value).then(response => {
        proxy.$modal.msgSuccess(title + "成功");
      });

      let params = {
        projectNo: row.projectNo
      }
      listAccounting(params).then((response) => {
        accountingList.value = response.data;
      });

    }
  }).then(() => {

  }).catch(() => { });
}

async function nextPhase() {
  //新版点击下一步 1.下一步按钮只开给需要审核的人 隐藏与显示 获取当前配置的环节规则 请求接口校验


  let allocationPar = {
    projectNo: projectNo.value
  }

  await getMatchingTotal(allocationPar).then(response => {
    console.log("人工成本addprofit", response);
    matchingFee.value = response

  });

  const response = await getAuditPermission(allocationPar).then((response) => {
    return response
  })

  console.log("校验绩效分配是否完成", response);
  if (response.data?.flag == false) {
    proxy.$modal.msgError(response.data.msg);
    return
  }

  if (personList.value.length == 0) {
    proxy.$modal.msgError("必须添加一名财务人员!");
    return
  }

  let flagcw = false
  //校验是否添加了财务
  for (let index = 0; index < personList.value.length; index++) {
    const element = personList.value[index];
    console.log("参与人员", element);

    if (element.postId == 6) {
      flagcw = true
      break;
    }
  }

  if (flagcw == false) {
    proxy.$modal.msgError("必须添加一名财务人员");
    return
  }


  let params = {
    projectNo: projectNo.value,
    id: 5//项目核算
  }
  //校验该环节的所有配置
  const result = await getCheck(params).then(response => {//立项阶段 id写死
    console.log("项目实施校验", response);
    return response
  });
  if (result.data.permission == false) {
    proxy.$modal.msgError(result.data.message);
    return
  }

  let param1 = {
    projectNo: projectNo.value,
  }
  const loadingInstance = ElLoading.service({ fullscreen: true, text: '加载中...' });
  await totalFee(param1).then(response => {
    bxFee.value = response.data;
    console.log("修改按钮获取总报销费用", bxFee.value);
  }).finally(() => {
    loadingInstance.close();
  });
  //判断最新报销费用是否和在添加利润计算的时候获取的金额是相等的 
  if (bxFee.value != accountingList.value[0]?.costOne) {
    proxy.$modal.msgError("最新报销费用为" + bxFee.value + "与填写利润计算时的报销费用" + accountingList.value[0]?.costOne + "不相等,请点击重新计算按钮获取最新的报销费用后重新提交");
    return
  }


  //判断最新人工成本费用是否和在添加利润计算的时候获取的金额是相等的 
  if (matchingFee.value != accountingList.value[0]?.laborCost) {
    proxy.$modal.msgError("最新人工成本费用为" + matchingFee.value + "与填写利润计算时的人工成本费用" + accountingList.value[0]?.laborCost + "不相等,请点击重新计算按钮获取最新的人工成本费用后重新提交");
    return
  }



  //检查项目提成是否和绩效分配的时候的相等
  const params1 = { projectNo: projectNo.value, current: "1" };
  const moneyRes = await getAllocationMoney(params1);
  if (moneyRes.data.allCommission != moneyRes.data.already) {
    proxy.$modal.msgError("项目提成有变化,已分配的项目提成为:" + moneyRes.data.already + ",最新的项目提成为:" + moneyRes.data.allCommission + ",请点击绩效分配按钮重新计算生成");
    return
  }

  //校验通过 更新当前阶段信息

  let updateParams = {
    id: currenrPhaseId.value,
  }
  const updateResult = await updatePhase(updateParams).then((response) => {
    console.log("更新阶段", response);
    return response
  });

  if (updateResult.data.status == 2) {//如果该环节已完成 插入下一个环节
    let addParams = {
      projectNo: projectNo.value,
      phaseId: 6,//项目归档
      remark: form.value.phaseRemark//留言
    }
    addPhase(addParams).then((response) => {

    })
  }

  proxy.$modal.msgSuccess("提交成功");
  status.value = 2
  open.value = false


}


function getCurrentDateTime() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  console.log("ssssssssssssssssss");
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};


function getCurrentDate() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  console.log("ssssssssssssssssss");
  return `${year}-${month}-${day}`;
};


initData()
onMounted(async () => {


  if (userStore.name == 'wuzg') {
    haveNext.value = true
  }

  await saleDetails(projectNo.value).then((response) => {
    form.value = response.data;
    contractAmount.value = response.data.contractAmount
    settlementAmount.value = response.data.settlementAmount
  });

  await getListParticipan(projectNo.value)

  // await getNextPer(projectNo.value);

  console.log("核算111111");


});



// loadUserColumnConfig()


// 所有可用列配置（可从接口获取）
const allColumns = [
  { label: "项目名称", prop: "projectName", visible: true },
  { label: "发起人", prop: "createUserName", visible: true },
  { label: "合同金额", prop: "contractAmount", visible: true },
  { label: "结算金额", prop: "settlementAmount", visible: true },
  { label: "项目阶段", prop: "phaseName", visible: true },
  { label: "立项日期", prop: "approvalDate", visible: true },
  { label: "上次更新时间", prop: "updateTime", visible: true },
  { label: "预计验收日期", prop: "acceptTime", visible: true },
  { label: "客户名称", prop: "customerName", visible: true },
  { label: "管家婆项目", prop: "housekeeperName", visible: true },
  { label: "项目类型", prop: "projectTypeName", visible: true },
  { label: "阶段确认人", prop: "joinPeople", visible: true },
  { label: "当前操作人", prop: "currentPeople", visible: true },

]

// 用户当前选择的列 props（由 el-checkbox-group 控制）
const selectedProps = ref([])


async function loadUserColumnConfig() {
  const res = await getUserTableConfig({ type: "accounting" })

  let defaultOrder = allColumns
    .filter(col => col.visible !== false) // 可以根据 visible 控制是否默认显示
    .map(col => col.prop)

  if (res.data && Array.isArray(res.data)) {
    // 使用用户保存的顺序（只保留合法的 prop）
    selectedProps.value = res.data.filter(prop =>
      allColumns.some(col => col.prop === prop)
    )
  } else {
    // 否则使用默认顺序
    selectedProps.value = defaultOrder
  }
}
// 取消按钮
function cancelPerson() {
  openOper.value = false;
  resetPer();
}


import useUserStore from '@/store/modules/user'

const userStore = useUserStore()
const tableRowClassName = ({ row }) => {
  return row.rowStatus == "1" ? 'success-row' : '';
};

</script>

<style>
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
</style>
